package leetcode.editor.cn.q1_300.q50;

/**
 * @author qidi
 * @date 2021-12-10 14:53:44
 */
class Q0061_RotateList {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || k == 0) return head;
            ListNode bak = head;

            ListNode last = null;
            int size = 0;
            while (bak != null) {
                size++;
                bak = bak.next;
                if (bak != null && bak.next == null) last = bak;
            }

            if (k % size == 0) return head;
            k = size - k % size;

            bak = head;
            while (k > 1) {
                k--;
                bak = bak.next;
            }
            ListNode newHead = bak.next;
            bak.next = null;

            last.next = head;
            return newHead;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0061_RotateList().new Solution();
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode node = null;
//        node = solution.rotateRight(node1, 2);
//
//        while (node != null) {
//            System.out.print(node.val + " -> ");
//            node = node.next;
//        }
//        System.out.println();

//        node = solution.rotateRight(node1, 4);
//
//        while (node != null) {
//            System.out.print(node.val + " -> ");
//            node = node.next;
//        }
//        System.out.println();

        node = solution.rotateRight(node1, 100);

        while (node != null) {
            System.out.print(node.val + " -> ");
            node = node.next;
        }
        System.out.println();
    }
}